package com.dkm.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

@Component
//(Filter)import package:javax.servlet
public class CORSFilter implements Filter {

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) servletRequest;
		HttpServletResponse response=(HttpServletResponse) servletResponse;
		//允许那些Origin发起跨域请求
		String origin=request.getHeader("Origin");
		// response.setHeader( "Access-Control-Allow-Origin", config.getInitParameter( "AccessControlAllowOrigin" ) );
		response.setHeader("Access-Control-Allow-Origin", origin);
		//允许请求的方法
		response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
		//多少秒内,不需要再发送预检验请求，可以缓存该结果
		response.setHeader("Access-Control-Max-Age", "3600");
		// 表明它允许跨域请求包含xxx头 Access-Control-Allow-Headers
		response.setHeader("Access-Control-Allow-Headers", "x-auth-token,Origin,Access-Token,X-Requested-With,Content-Type,Accept,token");
		//是否允许浏览器携带用户身份信息（cookie）
		response.setHeader("Access-control-Allow-Credentials", "true");

		//设置白名单
		response.addHeader("Access-Control-Expose-Headers", "REDIRECT,CONTEXTPATH");
		
		//prefight请求preflight 
        if (request.getMethod().equals( "OPTIONS" )) {
            response.setStatus( 200 );
            return;
        }
        chain.doFilter(servletRequest, response);
	}

}
